package com.sdy.dcsb.web.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sdy.common.model.BizException;
import com.sdy.common.model.Response;
import com.sdy.common.utils.Assert;
import com.sdy.common.utils.StringUtil;
import com.sdy.dcsb.biz.constants.OtherConstants;
import com.sdy.dcsb.biz.model.*;
import com.sdy.dcsb.biz.model.swagger.*;
import com.sdy.dcsb.biz.model.vo.EsbEncapsulationThreadVo;
import com.sdy.dcsb.biz.service.*;
import com.sdy.dcsb.web.controller.inboundservice.util.HttpReqUtil;
import com.sdy.dcsb.web.util.ChineseUtil;
import com.sdy.dcsb.web.util.JsonUtil;
import com.sdy.mvc.controller.BaseController;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author Snaky
 */
@Slf4j
@RestController
@RequestMapping("/EsbEncapsulation")
@Api(tags = "接口封装模块相关接口")
public class EsbEncapsulationController  extends BaseController {

    @Autowired
    private EsbEncapsulationService encapsulationService;
    @Autowired
    private EsbEncapsulationInputParamService inputParamService;
    @Autowired
    private EsbEncapsulationOutputParamService outputParamService;
    @Autowired
    private EsbEncapsulationRelateService relateService;
    @Autowired
    private EsbEncapsulationThreadService threadService;
    @Autowired
    private EsbEncapsulationParamConfService paramConfService;
    @Autowired
    private EsbAtomServiceService esbAtomServiceService;
    @Autowired
    private EsbProviderTreeService providerTreeService;
    @Autowired
    private UserOperationLogService userOperationLogService;
    @Autowired
    private EsbServiceAtomDeployService esbServiceAtomDeployService;
    @Autowired
    private EsbAppService esbAppService;
    @Autowired
    private EsbAdapderHttpService esbAdapderHttpService;
    @Autowired
    private EsbInboundMainService esbInboundMainService;
    @Autowired
    private EsbServiceTreeService esbServiceTreeService;
    @Autowired
    private EsbInboundHttpService esbInboundHttpService;
    @Autowired
    private EsbInboundParamService paramService;
    @Value("${server.port}")
    private String port;

    @GetMapping("/pageData")
    @ApiOperation(value = "接口封装参数配置页面数据接口", response = EsbEncapsulation.class)
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "String", name = "serviceCode", value = "接口编码/接口名称，可为空"),
            @ApiImplicitParam(dataType = "Integer", name = "current", value = "当前页，默认为1"),
            @ApiImplicitParam(dataType = "Integer", name = "size", value = "分页大小，默认为10")
    })
    public Response pageData(String serviceCode, Integer current, Integer size) throws Exception{
        if(current == null){
            current = 1;
        }
        if(size == null){
            size = 10;
        }
        serviceCode = ChineseUtil.decode(serviceCode);
        QueryWrapper<EsbEncapsulation> wrapper = new QueryWrapper<>();
        if(StringUtil.isNotBlank(serviceCode)){
            wrapper.like("service_code", serviceCode)
                    .or()
                    .like("service_name", serviceCode);
        }
        wrapper.orderByAsc("id");
        return Response.success(encapsulationService.page(new Page<>(current, size, 0),wrapper));
    }

    @GetMapping("/manage")
    @ApiOperation("已封装接口管理")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "Integer", name = "id", value = "已封装接口id，必传"),
            @ApiImplicitParam(dataType = "Integer", name = "type", value = "操作类型，必传。1 上线，2下线，3 删除")
    })
    public Response manage(Integer id, Integer type) throws Exception{
        Assert.isNull(id, "接口id为空");
        Assert.isNull(type, "操作类型为空");

        if(type > 3){
            throw new BizException("操作类型异常");
        }
        if(type == 3){
            encapsulationService.removeById(id);

            QueryWrapper<EsbEncapsulationRelate> wrapper1 = new QueryWrapper<>();
            wrapper1.eq("encapsulation_id",id);
            relateService.remove(wrapper1);

            QueryWrapper<EsbEncapsulationThread> wrapper2 = new QueryWrapper<>();
            wrapper2.eq("encapsulation_id",id);
            threadService.remove(wrapper2);

            QueryWrapper<EsbEncapsulationParamConf> wrapper3 = new QueryWrapper<>();
            wrapper3.eq("encapsulation_id",id);
            paramConfService.remove(wrapper3);

            QueryWrapper<EsbEncapsulationOutputParam> wrapper4 = new QueryWrapper<>();
            wrapper4.eq("encapsulation_id",id);
            outputParamService.remove(wrapper4);

            QueryWrapper<EsbEncapsulationInputParam> wrapper5 = new QueryWrapper<>();
            wrapper5.eq("encapsulation_id",id);
            inputParamService.remove(wrapper5);

            return Response.success(type);
        }

        UpdateWrapper<EsbEncapsulation> wrapper = new UpdateWrapper<>();
        wrapper.eq("id", id)
                .set("state",type);

        boolean flag = encapsulationService.update(wrapper);

        if(flag){
            return Response.success(type);
        }
        return Response.error("操作失败");
    }

    @GetMapping("/detailPageData")
    @ApiOperation(value = "接口封装列表信息接口", response = EsbEncapsulationDetailPageData.class)
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "Integer", name = "id", value = "已封装接口id，必传")
    })
    public Response detailPageData(Integer id) throws Exception{
        Assert.isNull(id, "接口id为空");

        EsbEncapsulation esbEncapsulation = encapsulationService.getById(id);
        if(esbEncapsulation == null){
            throw new BizException("接口id错误");
        }
        JSONObject data  = new JSONObject();
        // 基本信息
        data.put("base",esbEncapsulation);
        // 入参信息
        List<InputParamInfo> inputParams = inputParamService.getOutputParamInfo(id);
        data.put("input",inputParams);
        // 出参信息
        List<OutputParamInfo> outputParams = outputParamService.getOutputParamInfo(id);
        data.put("output",outputParams);
        // 关联接口信息
        List<RelateInfo> relateInfoList = relateService.getRelateInfo(id);
        data.put("relateInfo",relateInfoList);

        return Response.success(data);
    }

    @PostMapping(value = "/saveAllInfo", produces = "application/json;charset=UTF-8")
    @ResponseBody
    @ApiOperation("保存接口封装所有信息")
    public Response saveAllInfo(HttpServletRequest request, @RequestBody JSONObject json) throws Exception{
        BaseInfo baseInfo = json.getObject("baseInfo",BaseInfo.class);

        JSONArray relateInfo = json.getJSONArray("relateInfo");
        JSONArray threadInfo = json.getJSONArray("threadInfo");
        JSONArray paramConfInfo = json.getJSONArray("paramConfInfo");
        JSONArray outputParamInfo = json.getJSONArray("outputParamInfo");

        Assert.isNull(relateInfo,"关联接口为空");
        Assert.isNull(baseInfo,"基本信息为空");
        Assert.isNull(threadInfo,"线程设计信息为空");
        Assert.isNull(paramConfInfo,"入参配置信息为空");
        Assert.isNull(outputParamInfo,"出参信息为空");

        relateInfo = JsonUtil.distinctJSONArray(relateInfo);
        threadInfo = JsonUtil.distinctJSONArray(threadInfo);
        paramConfInfo = JsonUtil.distinctJSONArray(paramConfInfo);
        outputParamInfo = JsonUtil.distinctJSONArray(outputParamInfo);

        if(baseInfo.getServiceCode().contains(" ")){
            throw new BizException("编码中包含空格");
        }
        String code = OtherConstants.STANDARD_ENCAPSULATION_SERVICE_CODE_PREFIX
                .concat(baseInfo.getServiceCode())
                .concat(OtherConstants.STANDARD_ENCAPSULATION_SERVICE_CODE_SUFFIX);
        if(code.length() > OtherConstants.LIMIT_SERVICE_CODE_LENGTH){
            throw new BizException("服务编码过长，无法注册");
        }

        List<RelateInfo> relateInfoList = JSONArray.parseArray(relateInfo.toJSONString(),RelateInfo.class);
        List<ThreadInfo> threadInfoList = JSONArray.parseArray(threadInfo.toJSONString(),ThreadInfo.class);
        List<ParamConfInfo> paramConfInfoList = JSONArray.parseArray(paramConfInfo.toJSONString(),ParamConfInfo.class);
        List<OutputParamInfo> outputParamInfoList = JSONArray.parseArray(outputParamInfo.toJSONString(),OutputParamInfo.class);

        Response response = checkReasonable(relateInfoList, threadInfoList, paramConfInfoList,outputParamInfoList);
        if(!response.getSuccess()){
            return response;
        }
        Integer id = baseInfo.getId();
        // 新增还是修改标识，false:修改, true:新增
        boolean flag = false;
        if(id == null || id <= 0){
            flag = true;
        }
        // 新增/修改接口 都将接口设置为下线状态
        EsbEncapsulation encapsulation = new EsbEncapsulation();
        encapsulation.setServiceName(baseInfo.getServiceName())
                .setServiceCode(baseInfo.getServiceCode())
                .setOvertime(baseInfo.getOvertime())
                .setState(2);
        // 保存接口基本信息
        Response response1 = saveBaseInfo(id,encapsulation);
        if(!response1.getSuccess()){
            return response1;
        }
        id = (Integer) response1.getData();
        // 保存关联接口信息
        Response response2 = saveRelateInfo(id,relateInfoList);
        if(!response2.getSuccess()){
            return response2;
        }
        // 保存线程配置信息
        Response response3 = saveThreadInfo(id,threadInfoList);
        if(!response3.getSuccess()){
            return response3;
        }
        // 保存参数配置信息
        Response response4 = saveParamConfInfo(id,paramConfInfoList);
        if(!response4.getSuccess()){
            return response4;
        }
        // 保存出参配置信息
        Response response5 = saveOutputParamInfo(id,outputParamInfoList);
        if(!response5.getSuccess()){
            return response5;
        }
        // 自动注册接口
        if(flag){
            return automaticRegister(request,baseInfo.getOvertime(),encapsulation.getServiceName(),encapsulation.getServiceCode());
        }
        return Response.success();
    }

    @GetMapping("/getAllInfo")
    @ApiOperation(value = "封装接口所有配置信息", response = EsbEncapsulationAllInfo.class)
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "Integer", name = "id", value = "已封装接口id，必传")
    })
    public Response getAllInfo(Integer id) throws Exception{
        Assert.isNull(id,"接口id为空");

        EsbEncapsulation esbEncapsulation = encapsulationService.getById(id);
        if(esbEncapsulation == null){
            return Response.error("接口id不存在");
        }
        JSONObject data = new JSONObject();
        // 保存基本信息
        data.put("baseInfo", new BaseInfo()
                .setId(id)
                .setServiceCode(esbEncapsulation.getServiceCode())
                .setServiceName(esbEncapsulation.getServiceName())
                .setOvertime(esbEncapsulation.getOvertime()));
        // 查询关联接口信息
        List<RelateInfo> relates = relateService.getRelateInfo(id);
        data.put("relateInfo", relates);
        // 查询线程配置信息
        List<EsbEncapsulationThreadVo> threads = threadService.getThreadInfo(id);

        List<ThreadInfo> threadInfoList = new ArrayList<>();
        Set<Integer> numSet = new HashSet<>();
        for (EsbEncapsulationThreadVo threadVo: threads) {
            Integer num = threadVo.getNum();
            if(numSet.contains(num)){

                // 已存在同一线程
                int index = threadInfoList.size() - 1;
                ThreadInfo threadInfo = threadInfoList.get(index);
                threadInfo.getList().add(new RelateInfo().setId(threadVo.getId()).setName(threadVo.getName()));
                threadInfoList.set(index,threadInfo);
            } else {
                // 新的线程
                numSet.add(num);

                ThreadInfo threadInfo = new ThreadInfo();
                List<RelateInfo> relateInfoList = new ArrayList<>();
                relateInfoList.add(new RelateInfo().setId(threadVo.getId()).setName(threadVo.getName()));
                threadInfo.setNum(num).setList(relateInfoList);
                threadInfoList.add(threadInfo);
            }
        }
        data.put("threadInfo", threadInfoList);
        // 查询入参配置信息
        List<ParamConfInfo> paramConfList = paramConfService.getParamConfInfo(id);
        data.put("paramConfInfo", paramConfList);
        // 查询出参配置信息
        List<OutputParamInfo> outputParamInfoList = outputParamService.getOutputParamInfo(id);
        data.put("outputParamInfo", outputParamInfoList);

        return Response.success(data);
    }


    @PostMapping(value = "/simulation", produces = "application/json;charset=UTF-8")
    @ResponseBody
    @ApiOperation(value = "封装接口模拟测试")
    @ApiImplicitParam(dataType = "EsbEncapsulationSimulation", name = "json", value = "提交参数", required = true)
    public Response simulation(HttpServletRequest request, @RequestBody EsbEncapsulationSimulation json) throws Exception{
        Integer id = json.getId();
        Assert.isNull(id,"接口id为空");

        EsbEncapsulation esbEncapsulation = encapsulationService.getById(id);
        Assert.isNull(esbEncapsulation,"接口不存在");

        String url =  "http://localhost:"
                .concat(port)
                .concat(OtherConstants.PATH_ENCAPSULATION_REQUEST_MAPPING)
                .concat("/")
                .concat(OtherConstants.STANDARD_ENCAPSULATION_SERVICE_CODE_PREFIX)
                .concat(esbEncapsulation.getServiceCode())
                .concat(OtherConstants.STANDARD_ENCAPSULATION_SERVICE_CODE_SUFFIX);

        String result = HttpReqUtil.postJson(url, json.getParams().toJSONString(), "utf-8", "utf-8",
                Integer.valueOf(esbEncapsulation.getOvertime()), null);

        return JSONObject.parseObject(result,Response.class);
    }


    /**
     * 保存接口基本信息
     */
    private Response saveBaseInfo(Integer id, EsbEncapsulation encapsulation){

        if(id == null){

            List<EsbAtomservice> atomServices = esbAtomServiceService.selectAtomServiceByCode(encapsulation.getServiceCode());
            if(atomServices.size() >= 1) {
                return Response.error("对应原子服务编码已存在");
            }

            // 新增接口信息
            encapsulation.setCreateDate(new Date());
            boolean flag = encapsulationService.save(encapsulation);
            if(!flag){
                return Response.error("接口基本信息新增失败");
            }
            id = encapsulation.getId();
        } else {
            encapsulation.setId(id).setUpdateDate(new Date());
            boolean flag = encapsulationService.updateById(encapsulation);
            if(!flag){
                return Response.error("接口基本信息更新失败");
            }
        }
        return Response.success(id);
    }

    /**
     * 保存接口关联信息
     */
    private Response saveRelateInfo(Integer id,List<RelateInfo> relateInfoList){
        QueryWrapper<EsbEncapsulationRelate> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("encapsulation_id",id);
        relateService.remove(wrapper1);

        for (RelateInfo obj : relateInfoList) {
            EsbEncapsulationRelate relate = new EsbEncapsulationRelate();
            relate.setEncapsulationId(id)
                    .setServiceId(obj.getId())
                    .setCreateDate(new Date());
            boolean flag = relateService.save(relate);
            if(!flag){
                return Response.error("接口关联信息保存失败");
            }
        }
        return Response.success();
    }

    /**
     * 保存线程配置信息
     */
    private Response saveThreadInfo(Integer id, List<ThreadInfo> threadInfoList){
        QueryWrapper<EsbEncapsulationThread> wrapper2 = new QueryWrapper<>();
        wrapper2.eq("encapsulation_id",id);
        threadService.remove(wrapper2);

        for (ThreadInfo threadInfo :threadInfoList) {
            List<RelateInfo> relateInfoList = threadInfo.getList();
            for (int i = 0; i < relateInfoList.size(); i++) {
                RelateInfo relateInfo = relateInfoList.get(i);
                EsbEncapsulationThread encapsulationThread = new EsbEncapsulationThread();
                encapsulationThread.setEncapsulationId(id)
                        .setThreadOrder(threadInfo.getNum())
                        .setSequence(i + 1)
                        .setServiceId(relateInfo.getId())
                        .setCreateDate(new Date());
                boolean flag = threadService.save(encapsulationThread);
                if(!flag){
                    return Response.error("线程配置信息保存失败");
                }
            }
        }
        return Response.success();
    }

    /**
     * 保存入参配置信息
     */
    private Response saveParamConfInfo(Integer id, List<ParamConfInfo> paramConfInfoList){
        // 入参id集合
        List<Integer> paramIdList = paramConfInfoList.stream().map(ParamConfInfo::getParamId).collect(Collectors.toList());
        List<Integer> relatedParamList = paramConfInfoList.stream().map(ParamConfInfo::getRelatedParamId).collect(Collectors.toList());

        long disCount = paramIdList.stream().distinct().count();
        if(paramIdList.size() > disCount){
            Response.error("入参重复关联");
        }
        for (int i = 0; i < paramIdList.size(); i++) {
            if(paramIdList.get(i).equals(relatedParamList.get(i))){
                Response.error("禁止自关联");
            }
        }

        // 清空入参配置信息
        QueryWrapper<EsbEncapsulationParamConf> wrapper3 = new QueryWrapper<>();
        wrapper3.eq("encapsulation_id",id);
        paramConfService.remove(wrapper3);
        // 清空入参信息
        QueryWrapper<EsbEncapsulationInputParam> wrapper = new QueryWrapper<>();
        wrapper.eq("encapsulation_id",id);
        inputParamService.remove(wrapper);

        // 入参列表
        List<EsbInboundParam> paramList = paramService.getInputParamWithoutPureNode(id);
        // 入参关联信息map
       List<Integer> relatedParamIds = new ArrayList<>();

        for (ParamConfInfo paramInfo : paramConfInfoList) {
            EsbEncapsulationParamConf conf = new EsbEncapsulationParamConf();
            conf.setEncapsulationId(id)
                    .setThreadOrder(paramInfo.getThreadId())
                    .setServiceId(paramInfo.getServiceId())
                    .setInputParamId(paramInfo.getParamId())
                    .setRelatedServiceId(paramInfo.getRelatedServiceId())
                    .setRelatedParamId(paramInfo.getRelatedParamId())
                    .setCreateDate(new Date());
            relatedParamIds.add(paramInfo.getParamId());
            boolean flag = paramConfService.save(conf);
            if(!flag){
                return Response.error("入参配置信息保存失败");
            }
        }

        // 删除集合中存在匹配关系的入参
        paramList.removeIf(esbInboundParam -> relatedParamIds.contains(esbInboundParam.getId()));
        // 根据参数匹配关系，生成入参信息并保存
        for (EsbInboundParam esbInboundParam: paramList) {
            EsbEncapsulationInputParam inputParam =new EsbEncapsulationInputParam();
            inputParam.setEncapsulationId(id)
                    .setServiceId(esbInboundParam.getServiceId())
                    .setInputParamId(esbInboundParam.getId())
                    .setCreateDate(new Date());
            boolean flag = inputParamService.save(inputParam);
            if(!flag){
                return Response.error("自动生成的入参保存失败");
            }
        }

        return Response.success();
    }

    /**
     * 保存出参配置信息
     */
    private Response saveOutputParamInfo(Integer id,List<OutputParamInfo> outputParamInfoList){
        QueryWrapper<EsbEncapsulationOutputParam> wrapper4 = new QueryWrapper<>();
        wrapper4.eq("encapsulation_id",id);
        outputParamService.remove(wrapper4);

        for (OutputParamInfo outputParamInfo : outputParamInfoList) {
            EsbEncapsulationOutputParam outputParam = new EsbEncapsulationOutputParam();
            outputParam.setEncapsulationId(id)
                    .setServiceId(outputParamInfo.getServiceId())
                    .setOutputParamId(outputParamInfo.getParamId())
                    .setCreateDate(new Date());
            boolean flag = outputParamService.save(outputParam);
            if(!flag){
                return Response.error("出参配置信息失败");
            }
        }
        return Response.success();
    }

    /**
     * 自动注册接口
     * 原子服务编码：封装接口编码
     * 标准服务编码：zzGovBg.%s.SynReq
     * @param request 请求体，用户获取IP地址信息,保持日志
     * @param overTime 超时时间
     * @param serviceName 接口名称
     * @param serviceCode 接口编码
     */
    private Response automaticRegister(HttpServletRequest request,String overTime, String serviceName ,String serviceCode){
        // 注册接口
        EsbProviderTree esbProviderTree = providerTreeService.selectByName(OtherConstants.PROVIDER_TREE_NAME_ENCAPSULATION_MODULE);
        if(esbProviderTree == null){
            return Response.error("服务提供者中没有对应目录信息");
        }

        // 1、新增原子服务信息
        EsbAtomservice atomService = new EsbAtomservice();
        atomService.setSystemId(esbProviderTree.getCode())
                .setAtomserviceName(serviceName)
                .setAtomserviceCode(serviceCode)
                .setAdapterType("1")
                .setContentType("2")
                .setMaxClients("1000")
                .setAtomserviceVersion("1.0")
                .setStatus("1")
                .setOverTime(overTime)
                .setCreateTime(new Date());

        boolean flag = esbAtomServiceService.save(atomService);
        if(!flag){
            return Response.error("原子服务信息新增失败");
        }
        // 2、保存原子服务部署信息
        QueryWrapper<EsbApp> wrapper = new QueryWrapper<>();
        wrapper.likeRight("appname","subapp").orderByAsc("appname");
        List<EsbApp> result = esbAppService.list(wrapper);

        for (EsbApp esbApp : result) {
            EsbServiceAtomDeploy esbServiceAtomDeploy = new EsbServiceAtomDeploy()
                    .setDomainname("ESBAppDomain")
                    .setInstancename(esbApp.getAppname())
                    .setServiceid(atomService.getId())
                    .setStatus("1")
                    .setLastupdateTime(new Date())
                    .setDeploytype(1);
            userOperationLogService.savaUserLog(request, "新增原子服务部署信息："+
                    serviceCode + " ，app：" + esbApp.getAppname());
            boolean flag1 = esbServiceAtomDeployService.save(esbServiceAtomDeploy);
            if(!flag1){
                return Response.error("原子服务部署信息新增失败");
            }
        }

        //3、保存适配类型信息
        // 标准服务编码
        String code = OtherConstants.STANDARD_ENCAPSULATION_SERVICE_CODE_PREFIX
                .concat(serviceCode)
                .concat(OtherConstants.STANDARD_ENCAPSULATION_SERVICE_CODE_SUFFIX);
        if(code.length() > OtherConstants.LIMIT_SERVICE_CODE_LENGTH){
            return Response.error("服务编码过长，无法注册");
        }
        String url = "http://localhost:".
                concat(port)
                .concat(OtherConstants.PATH_ENCAPSULATION_REQUEST_MAPPING)
                .concat("/")
                .concat(code);
        EsbAdapderHttp esbAdapderHttp = new EsbAdapderHttp();
        esbAdapderHttp.setServiceUrl(url)
                .setRcharset("UTF-8")
                .setScharset("UTF-8")
                .setHttptype("2")
                .setId(atomService.getId());
        userOperationLogService.savaUserLog(request, "新增或修改原子服务的http适配类型信息："+ serviceCode);
        boolean flag2 = esbAdapderHttpService.save(esbAdapderHttp);
        if(!flag2){
            return Response.error("原子服务适配类型信息新增失败");
        }

        // 4、服务发布
        EsbInboundMain esbInboundMain = new EsbInboundMain();
        esbInboundMain.setServname(serviceName)
                .setServcode(code)
                .setServversion("1.0")
                .setStatus("1")
                .setAtomcode(serviceCode)
                .setOverTime("30000")
                .setCreateTime(new Date());
        userOperationLogService.savaUserLog(request, "新增服务信息：" + serviceCode);
        boolean flag3 = esbInboundMainService.save(esbInboundMain);
        if(!flag3){
            return Response.error("标准服务配置新增失败");
        }
        QueryWrapper<EsbServiceTree> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("name",OtherConstants.PROVIDER_TREE_NAME_ENCAPSULATION_MODULE);
        EsbServiceTree serviceTree = esbServiceTreeService.getOne(wrapper1);

        EsbServiceTree esbServiceTree = new EsbServiceTree();
        esbServiceTree.setCode(esbInboundMain.getServiceid())
                .setHaschildren(0)
                .setLvl(serviceTree.getLvl() + 1)
                .setName(serviceName)
                .setStatus("1")
                .setParId(serviceTree.getId());
        userOperationLogService.savaUserLog(request, "新增服务树目录：" + serviceName);
        boolean flag4 = esbServiceTreeService.save(esbServiceTree);
        if(!flag4){
            return Response.error("服务者树目录新增失败");
        }

        // 5、服务目录-服务接口信息保存
        EsbInboundHttp esbInboundHttp = new EsbInboundHttp();
        esbInboundHttp.setServiceid(esbInboundMain.getServiceid())
                .setHttptype(2);
        esbInboundHttpService.save(esbInboundHttp);
        userOperationLogService.savaUserLog(request, "新增服务http接入信息：" + serviceCode);

        // 6、服务目录-部署信息保存
        QueryWrapper<EsbApp> wrapper2 = new QueryWrapper<>();
        wrapper2.likeRight("appname","app").orderByAsc("appname");
        List<EsbApp> result1 = esbAppService.list(wrapper2);

        for (EsbApp esbApp : result1) {
            EsbServiceAtomDeploy esbServiceAtomDeploy = new EsbServiceAtomDeploy()
                    .setDomainname("ESBAppDomain")
                    .setInstancename(esbApp.getAppname())
                    .setServiceid(esbInboundMain.getServiceid())
                    .setStatus("1")
                    .setLastupdateTime(new Date())
                    .setDeploytype(0);
            userOperationLogService.savaUserLog(request, "新增服务部署信息："+
                    serviceCode + " ，app：" + esbApp.getAppname());
            boolean flag1 = esbServiceAtomDeployService.save(esbServiceAtomDeploy);
            if(!flag1){
                return Response.error("原子服务部署信息新增失败");
            }
        }

        return Response.success();
    }

    /**
     * 校验提交的接口信息是否规范，是否包含未关联接口
     */
    private Response checkReasonable( List<RelateInfo> relateInfoList , List<ThreadInfo> threadInfoList,
                                      List<ParamConfInfo> paramConfInfoList, List<OutputParamInfo> outputParamInfoList ){

        // 已关联的接口id数组
        List<Integer> relateServiceIds = relateInfoList.stream().map(RelateInfo::getId).collect(Collectors.toList());
        List<List<RelateInfo>> threadIds = threadInfoList.stream().map(ThreadInfo::getList).collect(Collectors.toList());
        List<Integer> paramConfServiceIds = paramConfInfoList.stream().map(ParamConfInfo::getServiceId).collect(Collectors.toList());
        List<Integer> paramConfRelatedServiceIds = paramConfInfoList.stream().map(ParamConfInfo::getRelatedServiceId).collect(Collectors.toList());
        List<Integer> outputParamServiceIds = outputParamInfoList.stream().map(OutputParamInfo::getServiceId).collect(Collectors.toList());

        Set<Integer> threadServiceIds = new HashSet<>();
        for(List<RelateInfo> relates: threadIds){
            threadServiceIds.addAll(relates.stream().map(RelateInfo::getId).collect(Collectors.toList()));
        }
        if(!relateServiceIds.containsAll(threadServiceIds)){
            return Response.error("线程中存在未关联接口");
        }
        if(!relateServiceIds.containsAll(paramConfServiceIds)){
            return Response.error("入参管理中存在未关联接口");
        }
        if(!relateServiceIds.containsAll(paramConfRelatedServiceIds)){
            return Response.error("入参管理中存在未关联接口");
        }
        if(!relateServiceIds.containsAll(outputParamServiceIds)){
            return Response.error("出参中存在未关联接口");
        }
        return Response.success();
    }
 }
